/**
 *    @file       listentask.cpp
 *
 *    @brief      
 *    @details
 *
 *    @version    1.0
 *    @date       02/19/2014 04:25:55 PM
 *
 *    @author     Theophilus (), wangtf418@gmail.com
 */
#include "listentask.h"
#include "netprocessthread.h"
#include "server.h"

listentask::listentask(csocket *sock, netprocessthread *netthread, const comargs *args /* = NULL */)
	: sockettask(sock, netthread, args), m_max_fd_size(100000)
{

}

listentask::~listentask()
{

}

bf_int_t listentask::init(bf_time_t timeout /* = SOCKTASK_TIMEOUT */, bf_int_t sock_buflen /*  = 102400 */)
{
	if (!m_socket)
	{
		return BF_ERROR;
	}

	m_max_fd_size = server::get()->get_baseconf().get_conf().m_max_fd_size;

	bf_int_t ret = m_socket->socket(SOCK_STREAM);
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}

	ret = m_socket->bind();
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}

	m_timeout = timeout;
	m_socket->set_nonblock_opt(true);
	m_socket->set_tcpnodelay_opt(true);

	m_socket->set_recvbuf_opt(sock_buflen);
	m_socket->set_sendbuf_opt(sock_buflen);

	ret = m_socket->listen();
	if (ret != BF_OK)
	{
		return BF_ERROR;
	}

	add_to_epoll();
	return BF_OK;
}

bf_int_t listentask::proc_msg(message *msg)
{
	return BF_OK;
}

bf_int_t listentask::process_io_event(bf_int_t events)
{
	if (events & BF_EPOLL_IN)
	{
		while (true)
		{
			m_accepted_socket = m_socket->accept(m_addr);
			if (m_accepted_socket <= 0)
			{
				break;
			}
			csocket *sock = new csocket(m_accepted_socket, m_addr);
			if (csocket::get_socket_num() > m_max_fd_size)
			{
				delete sock;
				continue;
			}

			commsgbody<csocket> *body = new commsgbody<csocket>(sock);
			m_netthread->send_msg(THD_TYPE_SERVER, RAND_THD_INDEX, 0, MSG_TYPE_RECV, body, m_taskid);
		}
	}
	else
	{
		return BF_ERROR;
	}
	return BF_OK;
}

bf_int_t listentask::recv_process()
{
	return BF_OK;
}

bf_int_t listentask::send_process()
{
	return BF_OK;
}

bf_int_t process_recv_packet(bf_char_t *buf, bf_size_t buflen)
{
	return BF_OK;
}

